package sc.love.boot.socket;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @ClassName SocketServer
 * @Description webSocket服务端
 * @Author 15393
 * @Date 2020/6/2 16:21
 * @Version V1.0
 */
@ServerEndpoint("/lts-one/{userId}")
@Component
public class SocketServer {

    private final static Logger log = LoggerFactory.getLogger(SocketServer.class);

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set，
    // 用来存放每个客户端对应的MyWebSocket对象。
    // 若要实现服务端与单一客户端通信的话，可以使用Map来存放，其中Key可以为用户标识
    private static ConcurrentHashMap<String,SocketServer> map = new ConcurrentHashMap<String,SocketServer>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    @OnOpen
    public void Open(Session session, @PathParam("userId") String userId) {
        this.session = session;
        map.put(userId, this);
        addOnlineCount();
        log.info("有新连接加入！当前在线人数为" + getOnlineCount());
    }

    @OnClose
    public void Close() {
        subOnlineCount();
        map.remove(this);
        log.info("有一连接关闭！当前在线人数为" + getOnlineCount());
    }


    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    @OnMessage
    public void Message(String message, Session session) {

        log.info("收到客户端消息" + message);

        JSONObject jsonObject = JSONObject.parseObject(message);
        String userId = jsonObject.getString("userId");
        String message1 = jsonObject.getString("message");
        try {
            sendMessage(userId, message1);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void sendMessage(String userId,String message) throws IOException {
        SocketServer socketServer = map.get(userId);
        socketServer.session.getBasicRemote().sendText("收到用户"+userId+"给您发的消息："+message);
    }

    @OnError
    public void Error(Session session, Throwable error) {
        log.info("发生错误");
        error.printStackTrace();
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        SocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        SocketServer.onlineCount--;
    }
}